package edu.hebtu.controller;

import edu.hebtu.mapper.impl.DistributionMapper;
import edu.hebtu.mapper.impl.ScoreMapper;
import edu.hebtu.mapper.impl.SubjectMapper;
import edu.hebtu.mapper.impl.UserMapper;
import edu.hebtu.pojo.Distribution;
import edu.hebtu.pojo.Score;
import edu.hebtu.pojo.Subject;
import edu.hebtu.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Controller
public class DistributionController {

    private final DistributionMapper distributionMapper;
    private final UserMapper userMapper;
    private final SubjectMapper subjectMapper;
    private final ScoreMapper scoreMapper;

    @Autowired
    public DistributionController(DistributionMapper distributionMapper, UserMapper userMapper, SubjectMapper subjectMapper, ScoreMapper scoreMapper) {
        this.distributionMapper = distributionMapper;
        this.userMapper = userMapper;
        this.subjectMapper = subjectMapper;
        this.scoreMapper = scoreMapper;
    }

    @RequestMapping("/distribute_trainer")
    public String distribute_trainer(Model model) {
        List<User> users = userMapper.findById(null);
        List<Subject> subjects = subjectMapper.findById(null);
        String subject_2 = "", subject_3 = "";
        for (Subject subject : subjects) {
            if (subject.getSubjectName().trim().equals("科目二")) {
                subject_2 = subject.getSubjectId();
            }
            if (subject.getSubjectName().trim().equals("科目三")) {
                subject_3 = subject.getSubjectId();
            }
        }
        users.removeIf(aValue -> aValue.getUserType() == 1);
        for (User user : users) {
            List<Distribution> distributions = distributionMapper.findByUserId(user.getUserId());
            for (Distribution distribution : distributions) {
                if (distribution.getSubjectId().trim().equals(subject_2.trim())) {
                    user.setDistributionSubjectTwoTrainerId(distribution.getCoachId());
                    user.setDistributionSubjectTwoTrainerName(userMapper.findById(distribution.getCoachId()).get(0).getName());
                }
                if (distribution.getSubjectId().trim().equals(subject_3.trim())) {
                    user.setDistributionSubjectThreeTrainerId(distribution.getCoachId());
                    user.setDistributionSubjectThreeTrainerName(userMapper.findById(distribution.getCoachId()).get(0).getName());
                }
            }
            if (user.getState().trim().equals("appear")) user.setState("正常");
            if (user.getState().trim().equals("licenced")) user.setState("已拿证");
        }
        model.addAttribute("users", users);
        return "admin/distribute";
    }

    @RequestMapping("/distribution_trainer/{userId}")
    public String distribution_trainer(@PathVariable("userId")String userId, Model model) {
        User user = userMapper.findById(userId).get(0);
        List<User> trainers = userMapper.findById(null);
        trainers.removeIf(aValue -> aValue.getUserType() == 0 || !aValue.getParent().equals(user.getParent()));
        List<User> trainer_2 = new ArrayList<User>();
        List<User> trainer_3 = new ArrayList<User>();
        List<Subject> subjects = subjectMapper.findById(null);
        String subject_2 = "", subject_3 = "";
        for (Subject subject : subjects) {
            if (subject.getSubjectName().trim().equals("科目二")) {
                subject_2 = subject.getSubjectId();
            }
            if (subject.getSubjectName().trim().equals("科目三")) {
                subject_3 = subject.getSubjectId();
            }
        }
        for (User trainer : trainers) {
            if (trainer.getSubjectId().trim().equals(subject_2)) {
                trainer_2.add(trainer);
            }
            if (trainer.getSubjectId().trim().equals(subject_3)) {
                trainer_3.add(trainer);
            }
        }
        trainer_2.sort(Comparator.comparing(User::getName).reversed());
        trainer_3.sort(Comparator.comparing(User::getName).reversed());
        model.addAttribute("trainer_2", trainer_2);
        model.addAttribute("trainer_3", trainer_3);
        List<Distribution> distributions = distributionMapper.findByUserId(user.getUserId());
        for (Distribution distribution : distributions) {
            if (distribution.getSubjectId().trim().equals(subject_2.trim())) {
                user.setDistributionSubjectTwoTrainerId(distribution.getCoachId());
                user.setDistributionSubjectTwoTrainerName(userMapper.findById(distribution.getCoachId()).get(0).getName());
            }
            if (distribution.getSubjectId().trim().equals(subject_3.trim())) {
                user.setDistributionSubjectThreeTrainerId(distribution.getCoachId());
                user.setDistributionSubjectThreeTrainerName(userMapper.findById(distribution.getCoachId()).get(0).getName());
            }
        }
        model.addAttribute("user", user);
        return "admin/distribute-trainer";
    }

    @RequestMapping("/distributeTrainer")
    public String distributeTrainer(User user, Model model) {
        List<Subject> subjects = subjectMapper.findById(null);

        user.setSex(userMapper.findById(user.getUserId()).get(0).getSex());         //由于前端是disabled，故接收不到性别信息，重新从数据库获取其性别信息

        List<User> trainer_2 = new ArrayList<User>();
        List<User> trainer_3 = new ArrayList<User>();
        List<User> trainers = userMapper.findById(null);
        trainers.removeIf(aValue -> aValue.getUserType() == 0 || !aValue.getParent().equals(user.getParent()));

        String subject_2 = "", subject_3 = "";
        for (Subject subject : subjects) {
            if (subject.getSubjectName().trim().equals("科目二")) {
                subject_2 = subject.getSubjectId();
            }
            if (subject.getSubjectName().trim().equals("科目三")) {
                subject_3 = subject.getSubjectId();
            }
        }

        for (User trainer : trainers) {
            if (trainer.getSubjectId().trim().equals(subject_2)) {
                trainer_2.add(trainer);
            }
            if (trainer.getSubjectId().trim().equals(subject_3)) {
                trainer_3.add(trainer);
            }
        }
        trainer_2.sort(Comparator.comparing(User::getName).reversed());
        trainer_3.sort(Comparator.comparing(User::getName).reversed());

        boolean flag_2 = false, flag_3 = false;
        List<Distribution> distributions = distributionMapper.findByUserId(user.getUserId());
        for (Distribution distribution : distributions) {
            if (distribution.getSubjectId().trim().equals(subject_2)) {
                flag_2 = true;
                if (!distribution.getCoachId().equals(user.getDistributionSubjectTwoTrainerId())) {     //数据库中的科目二教练与所选择的教练不同，即重新选择了教练
                    List<Score> scores = scoreMapper.findById(null);
                    boolean flag = false;
                    for (Score score : scores) {            //科目二是否通过
                        if (score.getSubjectId().trim().equals(subject_2) && score.getScore() >= subjectMapper.findById(subject_2).get(0).getPassLine()) {
                            flag = true;
                            break;
                        }
                    }
                    if (flag) {
                        model.addAttribute("msg", "科目二已通过，无法更换教练！！！");
                        user.setDistributionSubjectTwoTrainerId(distribution.getCoachId());
                        model.addAttribute("trainer_2", trainer_2);
                        model.addAttribute("trainer_3", trainer_3);
                        model.addAttribute("user", user);
                        return "admin/distribute-trainer";
                    } else {
                        distributionMapper.delete(distribution);
                        flag_2 = false;
                    }
                }
            }
            if (distribution.getSubjectId().trim().equals(subject_3)) {
                flag_3 = true;
                if (!distribution.getCoachId().equals(user.getDistributionSubjectThreeTrainerId())) {       //数据库中的科目三教练与所选择的教练不同，即重新选择了教练
                    List<Score> scores = scoreMapper.findById(null);
                    boolean flag = false;
                    for (Score score : scores) {            //科目三是否通过
                        if (score.getSubjectId().trim().equals(subject_3) && score.getScore() >= subjectMapper.findById(subject_3).get(0).getPassLine()) {
                            flag = true;
                            break;
                        }
                    }
                    if (flag) {
                        model.addAttribute("msg", "科目三已通过，无法更换教练！！！");
                        user.setDistributionSubjectTwoTrainerId(distribution.getCoachId());
                        model.addAttribute("trainer_2", trainer_2);
                        model.addAttribute("trainer_3", trainer_3);
                        model.addAttribute("user", user);
                        return "admin/distribute-trainer";
                    } else {
                        distributionMapper.delete(distribution);
                        flag_3 = false;
                    }
                }
            }
        }
        Distribution distribution = new Distribution();
        distribution.setUserId(user.getUserId());
        if (!(user.getDistributionSubjectTwoTrainerId() == null || user.getDistributionSubjectTwoTrainerId().trim().equals("")) && !flag_2) {
            distribution.setCoachId(user.getDistributionSubjectTwoTrainerId());
            distribution.setSubjectId(subject_2);
            distributionMapper.add(distribution);
        }
        if (!(user.getDistributionSubjectThreeTrainerId() == null || user.getDistributionSubjectThreeTrainerId().trim().equals("")) && !flag_3) {
            distribution.setCoachId(user.getDistributionSubjectThreeTrainerId());
            distribution.setSubjectId(subject_3);
            distributionMapper.add(distribution);
        }
        return "redirect:/distribute_trainer";
    }

}
